<template>
  <div class="knowledge-base">
    <!-- 头部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button @click="$router.push('/')" icon="ArrowLeft" circle />
        <h2>知识库管理</h2>
      </div>

      <div class="header-right">
        <el-button type="primary" @click="showUploadDialog = true" icon="Plus">
          新建知识库
        </el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="error" class="error">
        <el-alert
          title="加载失败"
          :description="error"
          type="error"
          show-icon
          @close="loadKnowledgeBase"
        />
      </div>

      <div v-else-if="knowledgeList.length === 0" class="empty">
        <el-empty description="还没有知识库">
          <el-button type="primary" @click="showUploadDialog = true">
            创建第一个知识库
          </el-button>
        </el-empty>
      </div>

      <div v-else class="knowledge-grid">
        <div
          v-for="item in knowledgeList"
          :key="item.id"
          class="knowledge-item"
        >
          <div class="knowledge-header">
            <div class="file-type-icon">
              <el-icon size="32" :color="getFileTypeColor(item.fileType)">
                <component :is="getFileTypeIcon(item.fileType)" />
              </el-icon>
            </div>
            <div class="knowledge-actions">
              <el-dropdown @command="handleCommand">
                <el-button type="text" icon="MoreFilled" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`view_${item.id}`" icon="View">
                      查看详情
                    </el-dropdown-item>
                    <el-dropdown-item :command="`delete_${item.id}`" icon="Delete" divided>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <div class="knowledge-info">
            <h4 class="knowledge-name">{{ item.name }}</h4>
            <p class="knowledge-description">{{ item.description || '暂无描述' }}</p>
            <div class="knowledge-meta">
              <span class="file-type">{{ getFileTypeLabel(item.fileType) }}</span>
              <span class="file-size" v-if="item.fileSize">{{ formatFileSize(item.fileSize) }}</span>
              <span class="create-time">{{ formatTime(item.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      :title="uploadMode === 'file' ? '上传文档' : '上传文本'"
      width="600px"
      @close="resetUploadForm"
    >
      <div class="upload-mode-tabs">
        <el-radio-group v-model="uploadMode" @change="resetUploadForm">
          <el-radio-button value="file">上传文档</el-radio-button>
          <el-radio-button value="text">输入文本</el-radio-button>
        </el-radio-group>
      </div>

      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="80px"
        style="margin-top: 20px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="uploadForm.name"
            placeholder="请输入知识库名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入描述（可选）"
          />
        </el-form-item>

        <el-form-item v-if="uploadMode === 'file'" label="文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :accept="acceptList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word 文档，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="uploadMode === 'text'" label="内容" prop="content">
          <el-input
            v-model="uploadForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入文本内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" :loading="uploading" @click="handleUpload">
          {{ uploadMode === 'file' ? '上传文档' : '保存文本' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="知识库详情"
      width="800px"
    >
      <div v-if="currentKnowledge" class="knowledge-detail">
        <div class="detail-header">
          <div class="detail-icon">
            <el-icon size="48" :color="getFileTypeColor(currentKnowledge.fileType)">
              <component :is="getFileTypeIcon(currentKnowledge.fileType)" />
            </el-icon>
          </div>
          <div class="detail-info">
            <h3>{{ currentKnowledge.name }}</h3>
            <p>{{ currentKnowledge.description || '暂无描述' }}</p>
            <div class="detail-meta">
              <el-tag>{{ getFileTypeLabel(currentKnowledge.fileType) }}</el-tag>
              <span v-if="currentKnowledge.fileSize">{{ formatFileSize(currentKnowledge.fileSize) }}</span>
              <span>{{ formatTime(currentKnowledge.createTime) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-content" v-if="currentKnowledge.content">
          <h4>内容预览</h4>
          <div class="content-preview">
            {{ currentKnowledge.content.substring(0, 1000) }}
            <span v-if="currentKnowledge.content.length > 1000">...</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadInstance} from 'element-plus'
import {Document, PictureRounded, UploadFilled} from '@element-plus/icons-vue'
import {knowledgeApi} from '@/api'
import {useUserStore} from '@/stores/user'
import type {KnowledgeBase} from '@/types'

const acceptList=ref(".pdf,.doc,.docx,.txt")
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const knowledgeList = ref<KnowledgeBase[]>([])
const loading = ref(true)
const error = ref('')
const showUploadDialog = ref(false)
const showDetailDialog = ref(false)
const uploadMode = ref<'file' | 'text'>('file')
const uploading = ref(false)
const currentKnowledge = ref<KnowledgeBase | null>(null)

// 表单引用
const uploadFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()

// 上传表单
const uploadForm = reactive({
  name: '',
  description: '',
  content: '',
  file: null as File | null
})

// 表单验证规则
const uploadRules: FormRules = {
  name: [
    { required: true, message: '请输入知识库名称', trigger: 'blur' },
    { min: 1, max: 200, message: '名称长度为1-200个字符', trigger: 'blur' }
  ],
  content: uploadMode.value === 'text' ? [
    { required: true, message: '请输入文本内容', trigger: 'blur' },
    { min: 1, message: '内容不能为空', trigger: 'blur' }
  ] : [],
  file: uploadMode.value === 'file' ? [
    { required: true, message: '请选择要上传的文件', trigger: 'change' }
  ] : []
}

// 计算属性
const userId = computed(() => userStore.userId)

// 组件挂载时加载数据
onMounted(() => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  loadKnowledgeBase()
})

// 加载知识库列表
const loadKnowledgeBase = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await knowledgeApi.getList(userId.value)
    if (response.code === 200) {
      knowledgeList.value = response.data
    } else {
      error.value = response.message || '获取知识库列表失败'
    }
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('加载知识库列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 处理文件选择
const handleFileChange = (file: any) => {
  uploadForm.file = file.raw
  // 如果名称为空，使用文件名
  if (!uploadForm.name) {
    uploadForm.name = file.name.replace(/\.[^/.]+$/, '')
  }
}

// 处理文件移除
const handleFileRemove = () => {
  uploadForm.file = null
}

// 重置上传表单
const resetUploadForm = () => {
  uploadForm.name = ''
  uploadForm.description = ''
  uploadForm.content = ''
  uploadForm.file = null
  uploadFormRef.value?.clearValidate()
  uploadRef.value?.clearFiles()
}

// 处理上传
const handleUpload = async () => {
  if (!uploadFormRef.value) return

  try {
    await uploadFormRef.value.validate()
    uploading.value = true

    if (uploadMode.value === 'file') {
      if (!uploadForm.file) {
        ElMessage.error('请选择要上传的文件')
        return
      }

      const response = await knowledgeApi.uploadFile(
        uploadForm.file,
        uploadForm.name,
        uploadForm.description,
        userId.value
      )

      if (response.code === 200) {
        ElMessage.success('文档上传成功！')
        showUploadDialog.value = false
        await loadKnowledgeBase()
      } else {
        ElMessage.error(response.message || '文档上传失败')
      }
    } else {
      const response = await knowledgeApi.uploadText({
        userId: userId.value,
        name: uploadForm.name,
        description: uploadForm.description,
        content: uploadForm.content
      })

      if (response.code === 200) {
        ElMessage.success('文本保存成功！')
        showUploadDialog.value = false
        await loadKnowledgeBase()
      } else {
        ElMessage.error(response.message || '文本保存失败')
      }
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}

// 处理下拉菜单命令
const handleCommand = async (command: string) => {
  const [action, id] = command.split('_')
  const knowledgeId = parseInt(id)

  if (action === 'view') {
    try {
      const response = await knowledgeApi.getDetail(knowledgeId)
      if (response.code === 200) {
        currentKnowledge.value = response.data
        showDetailDialog.value = true
      } else {
        ElMessage.error('获取详情失败')
      }
    } catch (error) {
      console.error('获取详情失败:', error)
      ElMessage.error('获取详情失败')
    }
  } else if (action === 'delete') {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个知识库吗？此操作不可恢复。',
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )

      const response = await knowledgeApi.delete(knowledgeId, userId.value)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        await loadKnowledgeBase()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }
}

// 获取文件类型图标
const getFileTypeIcon = (fileType: string) => {
  switch (fileType) {
    case 'pdf':
      return Document
    case 'word':
      return Document
    case 'text':
      return Document
    default:
      return PictureRounded
  }
}

// 获取文件类型颜色
const getFileTypeColor = (fileType: string) => {
  switch (fileType) {
    case 'pdf':
      return '#f56565'
    case 'word':
      return '#4299e1'
    case 'text':
      return '#48bb78'
    default:
      return '#a0aec0'
  }
}

// 获取文件类型标签
const getFileTypeLabel = (fileType: string) => {
  switch (fileType) {
    case 'pdf':
      return 'PDF文档'
    case 'word':
      return 'Word文档'
    case 'text':
      return '文本'
    default:
      return '未知'
  }
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}
</script>

<style scoped>
.knowledge-base {
  min-height: 100vh;
  background: #f5f6fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
}

.content {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.loading, .error {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.empty {
  background: white;
  border-radius: 12px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.knowledge-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.knowledge-item {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #f1f3f4;
  transition: all 0.3s ease;
}

.knowledge-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-color: #e3f2fd;
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.file-type-icon {
  padding: 8px;
  background: #f8f9fa;
  border-radius: 8px;
}

.knowledge-info {
  flex: 1;
}

.knowledge-name {
  margin: 0 0 8px 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.4;
}

.knowledge-description {
  margin: 0 0 12px 0;
  color: #7f8c8d;
  font-size: 0.9rem;
  line-height: 1.5;
}

.knowledge-meta {
  display: flex;
  gap: 12px;
  font-size: 0.8rem;
  color: #a0aec0;
}

.upload-mode-tabs {
  text-align: center;
}

.knowledge-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.detail-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.detail-info p {
  margin: 0 0 12px 0;
  color: #7f8c8d;
}

.detail-meta {
  display: flex;
  gap: 12px;
  align-items: center;
}

.detail-content h4 {
  margin: 0 0 12px 0;
  color: #2c3e50;
}

.content-preview {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  font-family: monospace;
  font-size: 0.9rem;
  line-height: 1.6;
  white-space: pre-wrap;
  max-height: 300px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .header {
    padding: 16px;
  }

  .content {
    padding: 16px;
  }

  .knowledge-grid {
    grid-template-columns: 1fr;
  }

  .knowledge-item {
    padding: 16px;
  }
}
</style>
